package com.gscitysfy.cus.drain.config;


import com.gscitysfy.cloudfrmwk.assistant.domain.Result;
import com.gscitysfy.cloudfrmwk.assistant.enums.ResultStatus;

import java.util.function.Function;

/**
 * 普通业务异常,异常消息保存在message中
 *
 * @author Smith
 */
public class BusinessException extends RuntimeException {
    private static final long serialVersionUID = 7653787970544957086L;
    /**
     * 业务异常编码,可为null
     */
    private Integer errorCode;

    private Object data;

    public BusinessException() {
    }

    public BusinessException(Exception e) {
        super(e);
    }

    public BusinessException(String msg, Exception e) {
        super(msg, e);
    }

    public BusinessException(String msg) {
        super(msg);
        this.errorCode = ResultStatus.FAIL.getCode();
    }

    public BusinessException(Integer errorCode) {
        this.errorCode = errorCode;
    }

    public BusinessException(String message, Integer errorCode) {
        super(message);
        this.errorCode = errorCode;
    }

    public BusinessException(Result<?> result) {
        super(result.getMessage());
        this.errorCode = result.getCode();
        this.data = result.getData();
    }

    public BusinessException(ResultStatus o) {
        super(o.getMessage());
        this.errorCode = o.getCode();
    }


    /**
     * 需要在msg前添加额外文本时调用
     *
     * @param o         异常代码常量
     * @param preFixMsg 前置msg
     */
    public BusinessException(ResultStatus o, String preFixMsg) {
        super(preFixMsg + o.getMessage());
        this.errorCode = o.getCode();
    }

    /**
     * 当你需要对错误message进行自定义时，请用这个方法
     *
     * @param o
     * @param msgFormatFunction
     */
    public BusinessException(ResultStatus o, Function<String, String> msgFormatFunction) {
        super(msgFormatFunction.apply(o.getMessage()));
        this.errorCode = o.getCode();
    }

    public Integer getErrorCode() {
        return errorCode;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}
